package com.ytjj.qmyx.mall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.dto.mqdto.DynamicCommentDto;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.IPUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.enums.UserBalanceSourceEnums;
import com.ytjj.qmyx.mall.mapper.DynamicEvaluateInfoMapper;
import com.ytjj.qmyx.mall.model.DynamicEvaluateInfo;
import com.ytjj.qmyx.mall.model.request.CommentRequest;
import com.ytjj.qmyx.mall.model.response.DynamicCommentResponse;
import com.ytjj.qmyx.mall.service.DynamicEvaluateInfoService;
import com.ytjj.qmyx.users.client.UsersClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class DynamicEvaluateInfoServiceImpl implements DynamicEvaluateInfoService {

    @Autowired
    private UsersClient usersClient;
    @Resource
    private DynamicEvaluateInfoMapper dynamicEvaluateInfoMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public DynamicCommentResponse insert(CommentRequest request, UsersResponse currentUser) {
        List<DynamicEvaluateInfo> checkExist = dynamicEvaluateInfoMapper.checkExist(request.getDynamicId(), currentUser.getId());
        DynamicCommentResponse response = new DynamicCommentResponse();
        if (!CollectionUtils.isEmpty(checkExist)) {
            DynamicEvaluateInfo oldVal = checkExist.get(0);
            response.setStarLevel(oldVal.getStarLevel());
            response.setScore(oldVal.getScore());
            return response;
        }
        DynamicEvaluateInfo dynamicEvaluateInfo = new DynamicEvaluateInfo();
        dynamicEvaluateInfo.setCreateTime(new Date());
        dynamicEvaluateInfo.setEvaluateId(request.getDynamicId());
        dynamicEvaluateInfo.setFlag(request.getFlag());
        dynamicEvaluateInfo.setStarLevel(request.getStarLevel());
        dynamicEvaluateInfo.setUserId(currentUser.getId());
        dynamicEvaluateInfo.setStatus(1);
        int score = doGiveScore(request.getUserId());
        dynamicEvaluateInfo.setScore(score);
        int count = dynamicEvaluateInfoMapper.insert(dynamicEvaluateInfo);

        response.setStarLevel(request.getStarLevel());
        response.setScore(score);
        try {
            usersClient.addScore(score, currentUser.getId(), "DYNAMIC_COMMENT");
        } catch (Exception e) {
            log.info("===用户赠送积分失败==={},{}", currentUser.getId(), score);
        }
        DynamicCommentDto dynamicCommentDto = new DynamicCommentDto();
        try {
            log.info("===新增评分埋点===");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String uuid = TokenUtil.getRequest().getHeader("uuid");
            String ip = IPUtil.getIpAddress(TokenUtil.getRequest());
            String channel = TokenUtil.getChannel();
            String source = TokenUtil.getSource();//ios/android
            dynamicCommentDto.setDynamicId(request.getDynamicId().toString());
            dynamicCommentDto.setId(String.valueOf(dynamicEvaluateInfo.getId()));
            dynamicCommentDto.setChannel(channel);
            dynamicCommentDto.setPlatform(source);
            dynamicCommentDto.setIp(ip);
            dynamicCommentDto.setUserId(request.getUserId().toString());
            dynamicCommentDto.setCreateTime(sdf.format(new Date()));
            dynamicCommentDto.setType(2);
            dynamicCommentDto.setUuid(uuid);
            dynamicCommentDto.setStarLevel(dynamicEvaluateInfo.getStarLevel());
//            rabbitTemplate.convertAndSend(QueueConstants.APP_DYNAMICCOMMENT, JSONObject.toJSONString(dynamicCommentDto));
        } catch (Exception e){
            log.error("===新增评分埋点异常==={}", JSONObject.toJSONString(dynamicCommentDto));
        }
        return response;
    }

    /**
     * 赠送积分
     */
    private int doGiveScore(Integer userId) {
        int score = 0;
        Random random = new Random();
        String giveNumStr = "";
        try {
            giveNumStr = redisService.get("dynamic:userId:" + userId.toString());
        } catch (Exception e) {}
        Integer giveNum = Integer.parseInt(StringUtils.isEmpty(giveNumStr) ? "0" : giveNumStr);

        Integer[] scores = {10, 15, 20};
        Integer[] lowerScores = {1, 2, 5};
        if (giveNum > 4) {
            score = lowerScores[random.nextInt(lowerScores.length - 1)];
        } else {
            score = scores[random.nextInt(scores.length - 1)];
        }
        if (score <= 0) {
            score = 1;
        }
        redisService.set("dynamic:userId:" + userId.toString(), String.valueOf(giveNum + 1));
        redisService.expire("dynamic:userId:" + userId.toString(), getSurplusSec());
        return score;
    }

    private long getSurplusSec() {
        LocalDate ld = LocalDate.now(ZoneId.systemDefault());
        LocalTime lt = LocalTime.of(23, 59, 59);
        LocalDateTime ldt = LocalDateTime.of(ld, lt);
        ldt.toInstant(ZoneOffset.of("+8")).toEpochMilli();

        return (ldt.toInstant(ZoneOffset.of("+8")).toEpochMilli() - System.currentTimeMillis()) / 1000;
    }

    public static void main(String[] args) {
        LocalDate ld = LocalDate.now(ZoneId.systemDefault());
        LocalTime lt = LocalTime.of(23, 59, 59);
        LocalDateTime ldt = LocalDateTime.of(ld, lt);
        ldt.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        System.out.println(ldt.format(DateTimeFormatter.ISO_DATE_TIME));
        System.out.println(ldt.toInstant(ZoneOffset.of("+8")).toEpochMilli());

        System.out.println((ldt.toInstant(ZoneOffset.of("+8")).toEpochMilli() - System.currentTimeMillis()) / 1000);
    }
}
